package com.yxy.controller;

import com.yxy.common.PageResult;
import com.yxy.common.Result;
import com.yxy.pojo.dto.BookDTO;
import com.yxy.pojo.dto.PageQueryDTO;
import com.yxy.pojo.vo.BookDetailVO;
import com.yxy.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/bfbbs/book")
@Slf4j
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String REDIS_BOOK_KEY = "book_";

    /**
     * 书籍分页查询
     * @param pageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> list(PageQueryDTO pageQueryDTO){
        log.info("书籍分页查询：{}", pageQueryDTO);
        PageResult pageResult = bookService.pageQuery(pageQueryDTO);
        return Result.success("", pageResult);
    }

    /**
     * 新增图书
     * @param bookDTO
     * @return
     */
    @PostMapping("/insert")
    public Result insert(@RequestBody BookDTO bookDTO){
        log.info("新增图书：{}", bookDTO);
        bookService.add(bookDTO);
        return Result.success("新增成功", null);
    }

    /**
     * 根据id查询书籍信息
     * @param id
     * @return
     */
    @GetMapping("/getDetailById/{id}")
    public Result<BookDetailVO> getById(@PathVariable int id){
        log.info("根据id查询书籍信息：{}", id);
        // 查询redis缓存
        String key = REDIS_BOOK_KEY + id;
        BookDetailVO redisBookVO = (BookDetailVO) redisTemplate.opsForValue().get(key);
        if(redisBookVO != null){
            return Result.success("", redisBookVO);
        }
        // 如果不存在，则查询数据库，并保存到redis中
        BookDetailVO vo = bookService.getById(id);
        redisTemplate.opsForValue().set(key, vo);
        return Result.success("", vo);
    }

    /**
     * 修改信息
     * @param bookDTO
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody BookDTO bookDTO){
        log.info("书籍修改信息：{}", bookDTO);
        bookService.update(bookDTO);
        clearCache(REDIS_BOOK_KEY + bookDTO.getId());
        return Result.success("修改成功", null);
    }

    /**
     * 清除缓存（暂时用不到批量删除缓存）
     * @param pattern
     */
    public void clearCache(String pattern){
        redisTemplate.delete(pattern);
    }
}
